package com.yao.guli.product.service.impl;

import com.yao.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.common.utils.PageUtils;
import com.yao.common.utils.Query;

import com.yao.guli.product.dao.PmsCategoryDao;
import com.yao.guli.product.entity.CategoryEntity;
import com.yao.guli.product.service.PmsCategoryService;


@Service("pmsCategoryService")
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryDao, CategoryEntity> implements PmsCategoryService {

    @Autowired
    private  PmsCategoryService  pmsCategoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithThree() {
//        1.遍历查找所有分类
        List<CategoryEntity>  entities = baseMapper.selectList(null);
        System.out.println(entities);


        //2、组装成父子的树形结构

        //2.1)、找到所有一级分类
        List<CategoryEntity> levelMenus = entities.stream()
                .filter(e -> e.getParentId() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu, entities));
                    return menu;
                })
                .sorted((menu, menu2) -> {
                    return (menu.getSort() == null ? 0 : menu.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());

        return levelMenus;

    }

    @Override
    public void removeMenuByID(List<Long> asList) {
        // TODO::1、检查当前删除的，是否有在其他地方引用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 递归查找所有菜单的子菜单
     *
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children =  all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentId() == root.getId();
        }).map(categoryEngity ->{
            // 1、找到子菜单
            categoryEngity.setChildren(getChildrens(categoryEngity, all));
            return categoryEngity;
        }).sorted((menu1, menu2) ->{
            // 2、菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort())- (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;

    }

}